package com.github.ghsea.framework.job.client;

import java.util.concurrent.ConcurrentHashMap;

import com.github.ghsea.framework.job.api.JobExecutor;
import com.github.ghsea.framework.job.common.JobExecuteResult;
import com.github.ghsea.framework.job.common.JobExecutorParams;

public class JobExecutorImpl implements JobExecutor {

	private ConcurrentHashMap<String, Object> name2Class = new ConcurrentHashMap<>();

	private JobExecuteHandler jobExecuteHandler;

	public JobExecutorImpl() {
		jobExecuteHandler = new AsyncJobExecuteHandler();
	}

	@Override
	public JobExecuteResult execute(JobExecutorParams params) {
		JobExecuteResult ret = null;
		try {
			Job target = (Job) findOrNewClass(params.getTargetClass());
			JobExecutionContext exeCtx = new JobExecutionContext();
			// target.execute(exeCtx);
			ret = jobExecuteHandler.handle(target, exeCtx);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ret;
	}

	private Object findOrNewClass(String className)
			throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Object target = name2Class.get(className);
		if (target != null) {
			return target;
		}

		synchronized (name2Class) {
			if (!name2Class.containsKey(className)) {
				Class<?> clz = Class.forName(className);
				target = clz.newInstance();
			}
		}
		name2Class.putIfAbsent(className, target);
		return target;
	}

}
